package cn.sinata.wanglin.neighbor.activity;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonObject;
import com.xilada.xldutils.activitys.CropImageActivity;
import com.xilada.xldutils.activitys.SelectPhotoDialog;
import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.BitmapUtils;
import com.xilada.xldutils.utils.FileUtils;
import com.xilada.xldutils.xldUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.db.dao.UserDao;
import cn.sinata.wanglin.model.Contact;
import cn.sinata.wanglin.model.Group;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.utils.ImageUtil;
import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class EditGroupInfoActivity extends TitleActivity {

    private String id;
    private String image;
    private String name;
    private String content;
    @BindView(R.id.image)
    SimpleDraweeView imageView;
    @BindView(R.id.tv_content)
    EditText tv_content;
    @BindView(R.id.et_name)
    EditText et_name;
    private String filePath;
    private String account;

    @Override
    protected int setContentId() {
        return R.layout.activity_edit_group_info;
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("编辑群资料");
        addRightButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editGroup();
            }
        });

        account = getIntent().getStringExtra("account");
        id = getIntent().getStringExtra("id");
        image = getIntent().getStringExtra("image");
        name = getIntent().getStringExtra("name");
        content = getIntent().getStringExtra("content");
        name = name == null ? "" : name;
        content = content == null ? "" : content;
        et_name.setText(name);
        tv_content.setText(content);
        imageView.setImageURI(ImageUtil.parseImageUri(image));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0) {
                if (data != null) {
                    filePath = data.getStringExtra("path");
                    imageView.setImageURI(Uri.parse("file://" + filePath));
                }
            } else if (requestCode == 1) {
                if (data != null) {
                    String filePath = data.getStringExtra(SelectPhotoDialog.DATA);
                    cropImage(filePath);
                }
            }
        }
    }

    void cropImage(String path){
        ActivityUtil.create(mContext)
                .go(CropImageActivity.class)
                .put("uri",path)
                .put("scale",1.478f)
                .startForResult(0);
    }

    @OnClick({R.id.tv_select_img})
    void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.tv_select_img:
                ActivityUtil.create(this)
                        .go(SelectPhotoDialog.class)
                        .startForResult(1);
                break;
        }
    }

    void editGroup() {
        content = tv_content.getText().toString().trim();
        name = et_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            showToast("群名称不能为空");
            return;
        }
        if (TextUtils.isEmpty(content)) {
            showToast("群介绍不能为空");
            return;
        }
        showDialog();
        if (TextUtils.isEmpty(filePath)) {
            noImage();
        } else {
            hasImage();
        }
    }

    void noImage() {
        HttpManager.editGroup(id, image, content, name)
                .subscribe(new ResultDataSubscriber<JsonObject>(this) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        //存储群用于聊天列表显示
                        UserDao.getInstance(mContext).saveUser(account,name,image);
                        setResult(RESULT_OK);
                        finish();
                    }
                });
    }

    void hasImage() {
        Observable.just(filePath)
                .subscribeOn(Schedulers.io())
                .flatMap(new Func1<String, Observable<File>>() {
                    @Override
                    public Observable<File> call(String s) {
                        String path = BitmapUtils.compressImagePath(s);
                        return Observable.just(new File(path));
                    }
                })
                .flatMap(new Func1<File, Observable<String>>() {
                    @Override
                    public Observable<String> call(File file) {
                        return HttpManager.uploadFile(mContext, file);
                    }
                })
                .flatMap(new Func1<String, Observable<ResultData<JsonObject>>>() {
                    @Override
                    public Observable<ResultData<JsonObject>> call(String s) {
                        image = s;
                        return HttpManager.editGroup(id, image, content, name);
                    }
                }).subscribe(new ResultDataSubscriber<JsonObject>(this) {
            @Override
            public void onSuccess(String msg, JsonObject jsonObject) {
                //存储群用于聊天列表显示
                UserDao.getInstance(mContext).saveUser(account,name,image);
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    @Override
    public void finish() {
        if (!TextUtils.isEmpty(xldUtils.PICDIR)) {
            FileUtils.deleteFiles(new File(xldUtils.PICDIR));
        }
        super.finish();
    }
}
